package fi.foyt.cs.persistence.dao.locale;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.locale.LocaleText;

public class LocaleTextDAO extends GenericDAO<LocaleText> {

  public LocaleText create(Long localeElementId, String locale, String text) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      LocaleText localeText = new LocaleText();
      localeText.setLocale(locale);
      localeText.setLocaleElementId(localeElementId);
      localeText.setText(text);
      
      entityManager.persist(localeText);
      entityManager.getTransaction().commit();
      return localeText;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public LocaleText findByLocaleElementIdAndLocale(Long localeElementId, String locale) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from LocaleText o where locale = :locale and localeElementId = :localeElementId");
    query.setParameter("localeElementId", localeElementId);
    query.setParameter("locale", locale);
    return getSingleResult(query);
  }
  
  public LocaleText updateText(LocaleText localeText, String text) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      localeText.setText(text);
      localeText = entityManager.merge(localeText);
      entityManager.getTransaction().commit();
      
      return localeText;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
}
